import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionHelper {
  /// 请求蓝牙权限
  static Future<bool> requestBluetoothPermissions(BuildContext context) async {
    // 检查并请求蓝牙权限
    Map<Permission, PermissionStatus> statuses;

    if (await Permission.bluetooth.request().isGranted &&
        await Permission.bluetoothConnect.request().isGranted &&
        await Permission.bluetoothScan.request().isGranted) {
      return true;
    }

    // 检查位置权限（蓝牙扫描需要）
    if (await Permission.location.request().isGranted) {
      return true;
    }

    // 再次检查权限状态
    statuses = await [
      Permission.bluetooth,
      Permission.bluetoothConnect,
      Permission.bluetoothScan,
      Permission.location,
    ].request();

    bool allGranted = true;
    statuses.forEach((permission, status) {
      if (!status.isGranted) {
        allGranted = false;
      }
    });

    if (!allGranted && context.mounted) {
      _showPermissionDialog(
        context,
        '蓝牙权限被拒绝',
        '请在设置中开启蓝牙和位置权限，以便连接翻译设备。',
      );
    }

    return allGranted;
  }

  /// 请求麦克风权限
  static Future<bool> requestMicrophonePermission(BuildContext context) async {
    PermissionStatus status = await Permission.microphone.request();

    if (status.isGranted) {
      return true;
    }

    if (status.isPermanentlyDenied && context.mounted) {
      _showPermissionDialog(
        context,
        '麦克风权限被拒绝',
        '请在设置中开启麦克风权限，以便录制语音进行翻译。',
      );
    }

    return status.isGranted;
  }

  /// 请求相机权限
  static Future<bool> requestCameraPermission(BuildContext context) async {
    PermissionStatus status = await Permission.camera.request();

    if (status.isGranted) {
      return true;
    }

    if (status.isPermanentlyDenied && context.mounted) {
      _showPermissionDialog(
        context,
        '相机权限被拒绝',
        '请在设置中开启相机权限，以便拍摄图片进行翻译。',
      );
    }

    return status.isGranted;
  }

  /// 请求视频通话权限（摄像头 + 麦克风）
  static Future<bool> requestVideoCallPermissions(BuildContext context) async {
    // 同时请求摄像头和麦克风权限
    Map<Permission, PermissionStatus> statuses = await [
      Permission.camera,
      Permission.microphone,
    ].request();

    bool cameraGranted = statuses[Permission.camera]?.isGranted ?? false;
    bool microphoneGranted = statuses[Permission.microphone]?.isGranted ?? false;

    // 检查权限状态
    if (cameraGranted && microphoneGranted) {
      return true;
    }

    if (!cameraGranted && !microphoneGranted) {
      if (context.mounted) {
        _showPermissionDialog(
          context,
          '视频通话权限被拒绝',
          '视频通话需要摄像头和麦克风权限，请在设置中开启这些权限。',
        );
      }
    } else if (!cameraGranted) {
      if (context.mounted) {
        _showPermissionDialog(
          context,
          '摄像头权限被拒绝',
          '视频通话需要摄像头权限，请在设置中开启摄像头权限。',
        );
      }
    } else if (!microphoneGranted) {
      if (context.mounted) {
        _showPermissionDialog(
          context,
          '麦克风权限被拒绝',
          '视频通话需要麦克风权限，请在设置中开启麦克风权限。',
        );
      }
    }

    return cameraGranted && microphoneGranted;
  }

  /// 检查视频通话权限状态
  static Future<bool> checkVideoCallPermissions() async {
    bool cameraGranted = await Permission.camera.isGranted;
    bool microphoneGranted = await Permission.microphone.isGranted;
    return cameraGranted && microphoneGranted;
  }

  /// 显示权限提示对话框
  static void _showPermissionDialog(
    BuildContext context,
    String title,
    String content,
  ) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              openAppSettings();
              Navigator.of(context).pop();
            },
            child: const Text('去设置'),
          ),
        ],
      ),
    );
  }
}